import useSyncState from "./useSynState";

const useChatX = () => {
  const [chatX, setChatX, getChatX] = useSyncState([]);

  const updateChatX = (message) => {
    if (typeof message === "object" && message !== null) {
      const { chatId } = message;

      const chatItem = getChatX().find((item) => item.chatId === chatId);

      if (chatItem) {
        setChatX((prevChatX) =>
          prevChatX.map((chat) => {
            return chat.chatId === chatItem.chatId
              ? { ...chat, content: `${chat.content}${message.content}`, status: message.status }
              : chat;
          })
        );
      } else {
        setChatX((prevChatX) => [...prevChatX, message]);
      }
    } else {
      throw new Error("message must be a object");
    }
  };

  const clearChatX = () => {
    setChatX([]);
  };

  return { chatX, updateChatX, clearChatX };
};

export default useChatX;
